package com.cyl.job;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyl.h5.domain.form.CancelOrderForm;
import com.cyl.h5.domain.vo.H5OrderVO;
import com.cyl.h5.service.H5OrderService;
import com.cyl.manager.aws.domain.entity.SystemStatistics;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class OrderJob {

    @Autowired
    private H5OrderService h5OrderService;

    @Autowired
    private OrderMapper orderMapper;
    

    @Autowired
    private RedisService redisService;
    
	@Value("${custom.synTaskEnable}")
	private boolean synTaskEnable;
	
    /**
     * 没分钟执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void cancelOrder(){
    	if(!synTaskEnable) {
			return ;
		}
		log.info("【取消订单任务开始任务开始】");
	   	String redisKey = "admin_cancel_order_123456";
	  	String redisValue = redisKey+"_"+System.currentTimeMillis();
	  	try{    
  			redisService.lock(redisKey,redisValue,60*1);
  	    	cancelOrderExe();
    	}catch (Exception e){
    		log.error("取消订单任务开始任务异常",e);
    	}finally {
	        try {
	        	redisService.unLock(redisKey,redisValue);
	        }catch (Exception e){
	            log.error("",e);
	        }
  	    }
    }

    
    public void cancelOrderExe(){
    	if(!synTaskEnable) {
			return ;
		}
        log.info("【取消订单任务开始】");
        int pageSize = 500;
        LocalDateTime startTime = LocalDateTime.now().plusHours(-24L);
        LocalDateTime endTime = LocalDateTime.now().plusMinutes(-18L);//20分钟
       
        QueryWrapper<Order> qw = new QueryWrapper<>();
        qw.eq("status", Constants.OrderStatus.NOTPAID);
        qw.eq("aftersale_status", 1);
        qw.between("create_time", startTime, endTime);
        
        PageHelper.startPage(1, pageSize);
        List<Order> orderList = orderMapper.selectList(qw);
        long total = ((com.github.pagehelper.Page) orderList).getTotal();
        if(total==0l || orderList == null || orderList.size()==0) {
        	return;
        }
        List<Long> idList = orderList.stream()
                .map(Order::getId)
                .collect(Collectors.toList());
        if(idList == null || idList.size()==0) {
        	return;
        }
        System.out.println(idList);
        CancelOrderForm request = new CancelOrderForm();
        request.setIdList(idList);
        h5OrderService.orderBatchCancel(orderList, idList);
//        if(total>pageSize) {
//        	try {
//				new Thread().sleep(3000);
//				this.cancelOrder();
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//        	
//        }
    }
    
    
//    /**
//     * 每天的1点20分20秒执行任务
//     */
//    @Scheduled(cron = "20 20 1 * * ?")
//    public void jobCancelOrder(){
//        log.info("【取消订单任务开始】");
//        LocalDateTime outTime = LocalDateTime.now().minusMinutes(20);
//        int outOrderNum =  orderMapper.jobCancelOrder(outTime);
//        log.info("【取消订单任务结束】"+"共计： "+outOrderNum);
//  
//    }

    /**
     * 每天的2点20分20秒执行任务
     */
    @Scheduled(cron = "20 20 2 * * ?")
    public void batchCompleteOrder(){
    	if(!synTaskEnable) {
			return ;
		}
//        log.info("【订单完成任务开始】");
//        QueryWrapper<Order> qw = new QueryWrapper<>();
//        qw.eq("status", Constants.OrderStatus.GET);
//        qw.eq("aftersale_status", 1);
//        qw.le("delivery_time", LocalDateTime.now().minusDays(15));
//        List<Order> orderList = orderMapper.selectList(qw);
//        h5OrderService.orderCompleteByJob(orderList);
//        log.info("【订单完成任务结束】,处理了：{}个订单",orderList.size());
    }

   

}
